package com.katze.boot.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.katze.boot.system.dao.CaptchaMapper;
import com.katze.boot.system.domain.SysCaptcha;
import com.katze.boot.system.service.CaptchaService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.Properties;

/**
 * 验证码
 */
@Service("sysCaptchaService")
public class CaptchaServiceImpl extends ServiceImpl<CaptchaMapper, SysCaptcha> implements CaptchaService {
    private final Producer producer;

    CaptchaServiceImpl() {
        Properties properties = new Properties();
        // 图片边框
        properties.put(Constants.KAPTCHA_BORDER, "no");
        //字体颜色
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR, "black");
        //文字间隔
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_CHAR_SPACE, "5");
        //验证码长度
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");
        //字体
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier,cmr10,宋体,楷体,微软雅黑");
        //文本集合，验证码值从此集合中获取 0qwertyuiopasdfghjklzxcvbnm
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_STRING, "0123456789");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);

        this.producer = defaultKaptcha;
    }

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new RuntimeException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();

        SysCaptcha captcha = new SysCaptcha();
        captcha.setUuid(uuid);
        captcha.setCode(code);
        //5分钟后过期
        captcha.setExpireTime(DateUtils.addMinutes(new Date(), 5));
        this.save(captcha);

        return producer.createImage(code);
    }

    @Override
    public boolean validate(String uuid, String code) {
        SysCaptcha captcha = this.getOne(new QueryWrapper<SysCaptcha>().eq("uuid", uuid));
        if (captcha == null) {
            return false;
        }

        //删除验证码
        this.removeById(uuid);

        return captcha.getCode().equalsIgnoreCase(code) && captcha.getExpireTime().getTime() >= System.currentTimeMillis();
    }
}
